package com.contain.gateway.security;

import com.alibaba.fastjson.JSON;
import com.contain.common.constant.AuthConstants;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.Payload;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther: tianchao
 * @Date: 2021/7/12 22:09
 * @Description:
 */

@Component
@Slf4j
public class AuthSignatureFilter implements GlobalFilter, Ordered {
    /**
     * Process the Web request and (optionally) delegate to the next {@code WebFilter}
     * through the given {@link GatewayFilterChain}.
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst(AuthConstants.AUTHORIZATION_KEY);
        if (StringUtils.isEmpty(token)){
            return chain.filter(exchange);
        }
        String realToken = token.replace("Bearer ", "");
        JWSObject jwsObject = JWSObject.parse(realToken);
        Payload payload = jwsObject.getPayload();
        JSONObject jsonObject = payload.toJSONObject();
        log.info(JSON.toJSONString(jsonObject));
        //向headers中放文件，记得build
        ServerHttpRequest host = exchange.getRequest().mutate().header("username", "hehe").build();
        //将现在的request 变成 change对象
        ServerWebExchange build = exchange.mutate().request(host).build();
        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
